import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import { Form, Input, Button, Select, Row, Col, Popover, Progress } from 'antd';
import styles from './Register.less';

const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;

const passwordStatusMap = {
  ok: <div className={styles.success}>强度：强</div>,
  pass: <div className={styles.warning}>强度：中</div>,
  poor: <div className={styles.error}>强度：太短</div>,
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

@connect(({ register, loading }) => ({
  register,
  submitting: loading.effects['register/submit'],
}))
@Form.create()
export default class Register extends Component {
  state = {
    count: 0,
    confirmDirty: false,
    visible: false,
    submitDisabled: false,
    help: '',
    nameHelp: '',
    nameValidateStatus: '',
    captchaHelp: '',
    captchaValidateStatus: '',
    prefix: '86',
    mobile: '',
  };

  componentWillReceiveProps(nextProps) {
    const account = this.props.form.getFieldValue('mail');
    if (nextProps.register.status === 'ok') {
      this.props.dispatch(
        routerRedux.push({
          pathname: '/user/register-result',
          state: {
            account,
          },
        })
      );
    }
    if (nextProps.register.type === 'name') {
      if ( nextProps.register.code === 'ok') {
        this.setState(
          {
            nameHelp: '',
            nameValidateStatus: 'success',
            submitDisabled: false,
          }
        )
      } else {
        this.setState(
          {
            nameHelp: '名字已经存在',
            nameValidateStatus: 'error',
            submitDisabled: true,
          }
        )
      }      
    }
    if (nextProps.register.type === 'captcha') {
      if ( nextProps.register.code === 'ok') {
        this.setState(
          {
            captchaHelp: '',
            captchaValidateStatus: 'success',
            submitDisabled: false,
          }
        )
      } else {
        this.setState(
          {
            captchaHelp: '验证码错误',
            captchaValidateStatus: 'error',
            submitDisabled: true,
          }
        )
      }      
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  onGetCaptcha = () => {
    let count = 59;
    this.setState({ count });
    this.interval = setInterval(() => {
      count -= 1;
      this.setState({ count });
      if (count === 0) {
        clearInterval(this.interval);
      }
    }, 1000);

    const { form } = this.props;
    const value = form.getFieldValue('mobile');
    this.props.dispatch({
      type: 'register/sendCaptcha',
      payload: {
        mobile : value,
      },
    });    
  };

  getPasswordStatus = () => {
    const { form } = this.props;
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        this.props.dispatch({
          type: 'register/submit',
          payload: {
            ...values,
            prefix: this.state.prefix,
          },
        });
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  handleCaptchaBlur = e => {
    debugger;
    const { form } = this.props;
    const mobile = form.getFieldValue('mobile');
    const { value } = e.target;
    this.props.dispatch({
      type: 'register/checkCaptcha',
      payload: {
        mobile : mobile,
        captcha : value,
      },
    });
  }

  handleCheckNameBlur = e => {
    const { value } = e.target;
    this.props.dispatch({
      type: 'register/checkName',
      payload: value,
    });
  }

  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('password')) {
      this.setState(
        {
          submitDisabled: true,
        }
      )
      callback('两次输入的密码不匹配!');
    } else {
      this.setState(
        {
          submitDisabled: false,
        }
      )
      callback();
    }
  };

  validateName = (rule, value, callback) => {
    if(typeof value === 'undefined' || !value || value.length < 4){
      this.setState(
        {
          nameHelp: '用户名长度不能小于4个字符',
          nameValidateStatus: 'error',
          submitDisabled: true,
        }
      )
      callback('error');
    } else if (value.length > 14) {
      this.setState(
        {
          nameHelp: '用户名长度不能大于14个字符',
          nameValidateStatus: 'error',
          submitDisabled: true,
        }
      )
      callback('error');
    } else {
      var regexp = /^1\d{10}$/;
      var found = value.match(regexp);
      if (found) {
        this.setState(
          {
            nameHelp: '不能用手机号码作为用户名',
            nameValidateStatus: 'error',
            submitDisabled: true,
          }
        )
        callback('error');
      } else {
        this.setState(
          {
            nameHelp: '',
            nameValidateStatus: 'success',
            submitDisabled: false,
          }
        )
        callback();      
      }
    }
  }

  validateMobile = (rule, value, callback) => {
    if(typeof value === 'undefined' || !value){
      callback();
    } else {
      var regexp = /^1\d{10}$/;
      var found = value.match(regexp);
      if(found) {
        this.props.dispatch({
          type: 'register/checkMobile',
          payload: value,
        });
        setTimeout(() => {
          if (this.props.register.type === 'mobile' && this.props.register.code === 'exist') {
            this.setState(
              {
                submitDisabled: true,
              }
            )
            callback('该手机已注册');
          } else {
            this.setState(
              {
                submitDisabled: false,
              }
            )
            callback();
          }
        }, 200);
      } else {
        callback('手机号格式错误!');
      }
    }
  };

  // validateCaptcha = (rule, value, callback) => {
  //   if(typeof value === 'undefined' || !value || value.length < 6){
  //     this.setState(
  //       {
  //         captchaHelp: '验证码长度不能小于6个字符',
  //         captchaValidateStatus: 'error',
  //       }
  //     )
  //     callback('error');
  //   } else {
  //     this.setState(
  //       {
  //         captchaHelp: '',
  //         captchaValidateStatus: 'success',
  //       }
  //     )
  //     callback();      
  //   }
  // };

  checkPassword = (rule, value, callback) => {
    if (!value) {
      this.setState({
        help: '请输入密码！',
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      if (!this.state.visible) {
        this.setState({
          visible: !!value,
        });
      }
      if (value.length < 6) {
        callback('error');
      } else {
        const { form } = this.props;
        if (value && this.state.confirmDirty) {
          form.validateFields(['confirm'], { force: true });
        }
        callback();
      }
    }
  };

  changePrefix = value => {
    this.setState({
      prefix: value,
    });
  };

  renderPasswordProgress = () => {
    const { form } = this.props;
    const value = form.getFieldValue('password');
    const passwordStatus = this.getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  render() {
    const { form, submitting } = this.props;
    const { getFieldDecorator } = form;
    const { count, prefix } = this.state;
    return (
      <div className={styles.main}>
        <h3>账号注册</h3>
        <Form onSubmit={this.handleSubmit}>
          <FormItem>
            <InputGroup compact>
              <Select
                size="large"
                value={prefix}
                onChange={this.changePrefix}
                style={{ width: '20%' }}
              >
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
              </Select>
              {getFieldDecorator('mobile', {
                rules: [
                  {
                    required: true,
                    message: '请输入手机号！',
                  },
                  // {
                  //   pattern: /^1\d{10}$/,
                  //   message: '手机号格式错误！',
                  // },
                  {
                    validator: this.validateMobile,
                  }
                ],
              })(<Input size="large" style={{ width: '80%' }} placeholder="11位手机号" />)}
            </InputGroup>
          </FormItem>
          <FormItem help={this.state.captchaHelp} validateStatus={this.state.captchaValidateStatus}>
            <Row gutter={8}>
              <Col span={16}>
                {getFieldDecorator('captcha', {
                  rules: [
                    {
                      required: true,
                      message: '请输入验证码！',
                    },
                    // {
                    //   validator: this.validateCaptcha,
                    // }
                  ],
                })(<Input size="large" onBlur={this.handleCaptchaBlur} placeholder="验证码" />)}
              </Col>
              <Col span={8}>
                <Button
                  size="large"
                  disabled={count}
                  className={styles.getCaptcha}
                  onClick={this.onGetCaptcha}
                >
                  {count ? `${count} s` : '获取验证码'}
                </Button>
              </Col>
            </Row>
          </FormItem>
          <FormItem help={this.state.help} hasFeedback>
            <Popover
              content={
                <div style={{ padding: '4px 0' }}>
                  {passwordStatusMap[this.getPasswordStatus()]}
                  {this.renderPasswordProgress()}
                  <div style={{ marginTop: 10 }}>
                    请至少输入 6 个字符。请不要使用容易被猜到的密码。
                  </div>
                </div>
              }
              overlayStyle={{ width: 240 }}
              placement="right"
              visible={this.state.visible}
            >
              {getFieldDecorator('password', {
                rules: [
                  {
                    validator: this.checkPassword,
                  },
                ],
              })(<Input size="large" type="password" placeholder="至少6位密码，区分大小写" />)}
            </Popover>
          </FormItem>
          <FormItem hasFeedback>
            {getFieldDecorator('confirm', {
              rules: [
                {
                  required: true,
                  message: '请确认密码！',
                },
                {
                  validator: this.checkConfirm,
                },
              ],
            })(<Input size="large" type="password" placeholder="确认密码" />)}
          </FormItem>
          <FormItem help={this.state.nameHelp} validateStatus={this.state.nameValidateStatus} hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                // {
                //   required: true,
                //   message: '用户名长度不能小于4个字符',
                // },
                {
                  validator: this.validateName,
                },
              ],
            })(<Input onBlur={this.handleCheckNameBlur} size="large" placeholder="用户名，限制4到14个字符" />)}
          </FormItem>
          <FormItem hasFeedback>
            {getFieldDecorator('mail', {
              rules: [
                {
                  required: true,
                  message: '请输入邮箱地址！',
                },
                {
                  type: 'email',
                  message: '邮箱地址格式错误！',
                },
              ],
            })(<Input size="large" placeholder="邮箱地址" />)}
          </FormItem>
          <FormItem>
            <Button
              disabled={this.state.submitDisabled}
              size="large"
              loading={submitting}
              className={styles.submit}
              type="primary"
              htmlType="submit"
            >
              注册
            </Button>
            <Link className={styles.login} to="/user/login">
              使用已有账户登录
            </Link>
          </FormItem>
        </Form>
      </div>
    );
  }
}
